<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-title">{{currentYearMonth}}</view>
    </view>

    <!-- 日历主体 -->
    <view class="calendar">
      <!-- 星期标题 -->
      <view class="week-row">
        <view class="week-item" v-for="(item, index) in weekDays" :key="index" :class="{'weekend': index === 0 || index === 6}">
          {{item}}
        </view>
      </view>
      
      <!-- 日期格子 -->
      <view class="date-container">
        <view 
          v-for="(day, index) in days" 
          :key="index" 
          class="date-item" 
          :class="{
            'selected': day.selected,
            'today': day.isToday,
            'other-month': !day.currentMonth,
            'weekend': day.isWeekend
          }"
          @tap="selectDate(day)"
        >
          <view class="date-num">{{day.date}}</view>
        </view>
      </view>
    </view>

    <!-- 打卡记录 -->
    <view class="record-container">
      <!-- 加载状态 -->
      <view class="loading-container" v-if="isLoading">
        <view class="loading-icon"></view>
        <text class="loading-text">加载中...</text>
      </view>
      
      <block v-else-if="hasRecord">
        <view class="record-content">
          <view class="record-header">
            <text class="record-title">打卡记录</text>
          </view>
          <view class="record-item">
            <view class="record-label">上班时间</view>
            <view class="record-time">{{checkInTime || '未打卡'}}</view>
          </view>
          <view class="record-item">
            <view class="record-label">下班时间</view>
            <view class="record-time">{{checkOutTime || '未打卡'}}</view>
          </view>
        </view>
      </block>
      <view v-else class="empty-container">
        <view class="empty-icon">
          <view class="icon-container">
            <text class="icon-text">无</text>
          </view>
        </view>
        <text class="empty-text">暂无打卡信息</text>
      </view>
    </view>

    <!-- 底部功能区 -->
    <view class="footer">
      <button class="refresh-btn" @tap="refreshData">刷新数据</button>
    </view>
  </view>
</template>

<script>
import {pushPhoto, submitAttendanceRecord} from "@/api/kq/update";
import config from '@/config';

export default {
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      days: [],
      selectedDate: new Date(),
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      hasRecord: false,
      checkInTime: '',
      checkOutTime: '',
      isLoading: false,
      fileList: [],
      isEditing: false,
      isSubmitting: false,
      recordInfo: null,
      editedInfo: {
        username: '',
        today: '',
        firstRecord: '',
        endRecord: ''
      }
    }
  },
  computed: {
    currentYearMonth() {
      return `${this.currentYear}年${this.currentMonth}月`
    }
  },
  onLoad() {
    // 检查登录状态
    const token = uni.getStorageSync('App-Token');
    if (!token) {
      uni.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }

    this.initCalendar()
    this.getAttendanceRecord()
  },
  onPullDownRefresh() {
    this.refreshData()
  },
  methods: {
    // 初始化日历数据
    initCalendar() {
      const date = new Date(this.currentYear, this.currentMonth - 1, 1)
      const today = new Date()
      
      // 获取当月第一天是星期几
      const firstDayOfWeek = date.getDay()
      
      // 获取当月天数
      const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate()
      
      // 获取上月天数
      const daysInLastMonth = new Date(this.currentYear, this.currentMonth - 1, 0).getDate()
      
      let days = []
      
      // 填充上月日期
      for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        const day = daysInLastMonth - i
        const dayDate = new Date(this.currentYear, this.currentMonth - 2, day)
        days.push({
          date: day,
          fullDate: this.formatDate(dayDate),
          currentMonth: false,
          isToday: false,
          selected: false,
          isWeekend: dayDate.getDay() === 0 || dayDate.getDay() === 6
        })
      }
      
      // 填充当月日期
      for (let i = 1; i <= daysInMonth; i++) {
        const dayDate = new Date(this.currentYear, this.currentMonth - 1, i)
        const isToday = i === today.getDate() && 
                        this.currentMonth === today.getMonth() + 1 && 
                        this.currentYear === today.getFullYear()
        
        days.push({
          date: i,
          fullDate: this.formatDate(dayDate),
          currentMonth: true,
          isToday: isToday,
          selected: isToday,
          isWeekend: dayDate.getDay() === 0 || dayDate.getDay() === 6
        })
        
        if (isToday) {
          this.selectedDate = dayDate
        }
      }
      
      // 计算需要的行数 (最多6行)
      const totalDaysNeeded = 42 // 6行 x 7天
      
      // 填充下月日期
      const remainingDays = totalDaysNeeded - days.length
      for (let i = 1; i <= remainingDays; i++) {
        const dayDate = new Date(this.currentYear, this.currentMonth, i)
        days.push({
          date: i,
          fullDate: this.formatDate(dayDate),
          currentMonth: false,
          isToday: false,
          selected: false,
          isWeekend: dayDate.getDay() === 0 || dayDate.getDay() === 6
        })
      }
      
      this.days = days
    },
    
    // 选择日期
    selectDate(day) {
      // 取消之前选择的日期
      this.days.forEach(d => d.selected = false)
      
      // 设置新选择的日期
      day.selected = true
      
      // 更新选择的日期
      if (day.currentMonth) {
        this.selectedDate = new Date(this.currentYear, this.currentMonth - 1, day.date)
      } else {
        if (day.date > 20) {
          // 上月日期
          this.selectedDate = new Date(this.currentYear, this.currentMonth - 2, day.date)
        } else {
          // 下月日期
          this.selectedDate = new Date(this.currentYear, this.currentMonth, day.date)
        }
      }
      
      // 获取选定日期的打卡记录
      this.getAttendanceRecord()
    },
    
    // 获取打卡记录数据
    getAttendanceRecord() {
      const token = uni.getStorageSync('App-Token');
      
      if (!token) {
        uni.showToast({
          title: '未登录，请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/index'
          });
        }, 1500);
        return;
      }

      // 添加token检查
      if (!token.startsWith('Bearer ')) {
        uni.setStorageSync('App-Token', 'Bearer ' + token);
      }

      const finalToken = token.startsWith('Bearer ') ? token : 'Bearer ' + token;
      const userId = this.$store.getters.userId;
      const date = this.formatFullDate(this.selectedDate);

      this.isLoading = true;
      uni.request({
        url: config.baseUrl + '/kq/record/getTime/' + userId,
        method: 'GET',
        data: {
          date: date
        },
        header: {
          'Authorization': finalToken
        },
        success: (res) => {
          if (res.data.code === 200) {
            const records = res.data.data;
            // 检查是否有记录
            if (records && records.length > 0) {
              const record = records[0];
              this.recordInfo = {
                id: record.id,
                date: record.date,
                username: record.name,
                startTime: record.startTime,
                endTime: record.endTime
              };
              this.checkInTime = record.startTime || '未打卡';
              this.checkOutTime = record.endTime || '未打卡';
              this.hasRecord = true;
            } else {
              // 没有找到记录
              this.recordInfo = null;
              this.checkInTime = '未打卡';
              this.checkOutTime = '未打卡';
              this.hasRecord = false;
            }
          } else if (res.data.code === 401) {
            // 认证失败，尝试刷新token
            uni.removeStorageSync('App-Token');
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/login/index'
              });
            }, 1500);
          } else {
            this.hasRecord = false;
            this.checkInTime = '未打卡';
            this.checkOutTime = '未打卡';
            uni.showToast({
              title: res.data.msg || '获取打卡记录失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          this.hasRecord = false;
          this.checkInTime = '未打卡';
          this.checkOutTime = '未打卡';
          uni.showToast({
            title: '获取打卡记录失败: ' + JSON.stringify(error),
            icon: 'none'
          });
        },
        complete: () => {
          this.isLoading = false;
          uni.stopPullDownRefresh();
        }
      });
    },
    
    // 刷新数据
    refreshData() {
      this.getAttendanceRecord()
    },
    
    // 格式化日期 (MM-DD)
    formatDate(date) {
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${month}-${day}`
    },
    
    // 格式化完整日期 (YYYY-MM-DD)
    formatFullDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #f5f7fa;
}

.container {
  padding-bottom: 40rpx;
}

.header {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  
  .header-title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }
}

.calendar {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .week-row {
    display: flex;
    padding: 10rpx 0 20rpx;
    border-bottom: 1rpx solid #f1f1f1;
    
    .week-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      
      &.weekend {
        color: #999;
      }
    }
  }
  
  .date-container {
    display: flex;
    flex-wrap: wrap;
    padding-top: 20rpx;
    
    .date-item {
      width: 14.28%;
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      margin-bottom: 10rpx;
      
      .date-num {
        font-size: 32rpx;
        color: #333;
      }
      
      &.other-month .date-num {
        color: #ccc;
      }
      
      &.weekend:not(.other-month) .date-num {
        color: #999;
      }
      
      &.today {
        color: #007aff;
      }
      
      &.selected {
        .date-num {
          width: 60rpx;
          height: 60rpx;
          border-radius: 30rpx;
          background-color: #4095ff;
          color: #fff;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}

.record-container {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  min-height: 300rpx;
  position: relative;
  
  .loading-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
    .loading-icon {
      width: 40rpx;
      height: 40rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #4095ff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    .loading-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  }
  
  .record-content {
    .record-header {
      margin-bottom: 30rpx;
      
      .record-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }
    }
    
    .record-item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .record-label {
        color: #666;
        font-size: 28rpx;
      }
      
      .record-time {
        color: #333;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }
  
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 250rpx;
    
    .empty-icon {
      margin-bottom: 20rpx;
      
      .icon-container {
        width: 120rpx;
        height: 120rpx;
        background-color: #f5f5f5;
        border-radius: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        
        .icon-text {
          font-size: 36rpx;
          color: #999;
        }
      }
    }
    
    .empty-text {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.footer {
  padding: 20rpx;
  
  .refresh-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #4095ff;
    color: #fff;
    border-radius: 8rpx;
    font-size: 30rpx;
  }
}
</style> 